package com.example.SimpleGateway.CommonUtil;



import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;


import com.example.SimpleGateway.constant.Constant;
import com.example.SimpleGateway.model.RSMessage;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.netty.util.internal.StringUtil;
import org.springframework.util.StringUtils;

/**
 * Created by qihao on 2018/2/14.
 */
public class HttpUtil {

    /**
     * get请求（）
     * @param urlStr
     * @param params 格式:key1=value1&key2=value2
     * @param path 格式:a/b/c
     * @return
     */
    public static RSMessage doGet(String urlStr, String params,String path) throws Exception {
        RSMessage result = null;
        URL url = null;
        if(!StringUtils.isEmpty(params)){
           url = new URL(urlStr + params);
        }
        if(!StringUtils.isEmpty(path)){
            url = new URL(urlStr + path);
        }
        if(url == null){
            url = new URL(urlStr);
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000)
                .setSocketTimeout(3000).build();
        HttpGet httpGet = new HttpGet(url.toURI());// 创建httpGet
        httpGet.setConfig(requestConfig);
        httpGet.setHeader("Accept", "application/json");
        httpGet.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpGet);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                result = new RSMessage(Constant.RESULT_SUCCESS,jsonString);
            }
            else{
                result = new RSMessage(Constant.RESULT_ERROR,"Http Error,ERROR CODE: " + state);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * post请求（）
     * @param urlStr
     * @param params 格式:key1=value1&key2=value2
     * @return
     */
    public static RSMessage doPostByParams(String urlStr, String params) throws Exception {
        RSMessage result = null;
        URL url = new URL(urlStr );
        URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000)
                       .setSocketTimeout(3000).build();
        HttpPost httpPost = new HttpPost(url.toURI());// 创建httpPost
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                result = new RSMessage(Constant.RESULT_SUCCESS,jsonString);
            }
            else{
                result = new RSMessage(Constant.RESULT_ERROR,"Http Error,ERROR CODE: " + state);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /**
     * post请求（）
     * @param urlStr
     * @body body
     * @return
     */
    public static RSMessage doPostByBody(String urlStr, String body){

        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        try {
            URL url = new URL(urlStr);
            // Configure and open a connection to the site you will send the request
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            // 设置doOutput属性为true表示将使用此urlConnection写入数据
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("POST");
            // Post 请求不能使用缓存
            urlConnection.setUseCaches(false);
            urlConnection.setRequestProperty("Content-Length", String.valueOf(body.length()));
            // 定义待写入数据的内容类型，设置为application/json类型
            urlConnection.setRequestProperty("content-type", "application/json");
            urlConnection.setConnectTimeout(3000);
            urlConnection.setReadTimeout(3000);
        // 得到请求的输出流对象


            outputStream = urlConnection.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);

            outputStreamWriter.write(body);
            outputStreamWriter.flush();
            //响应失败
            if (urlConnection.getResponseCode() != 200) {
                return new RSMessage(Constant.RESULT_ERROR, "HTTP Request is not success, Response code is " + urlConnection.getResponseCode());
            }

            //接收响应流
            inputStream = urlConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);

            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }

        }catch (Exception e){
            return  new RSMessage(Constant.RESULT_SUCCESS, Constant.ERROR_SYSTEM+e.getMessage());
        }finally {
            try {
                if (outputStreamWriter != null) {
                    outputStreamWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return  new RSMessage(Constant.RESULT_SUCCESS, resultBuffer.toString());
    }
}
